﻿using T.Common.Domain.Common;
using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.Common.Domain.Manufacture;
using AutoMapper;
using RedDragon.ERP.ErroCodeEnum;
using Yitter.IdGenerator;
using RedDragon.Common.Domain.Enterprise;

namespace RedDragon.ERP.API.Application.Commands.WorkCenter
{
    public class CreateWorkCenterHandler : IRequestHandler<CreateWorkCenterCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 工作表仓储
        /// </summary>
        public readonly IBaseRepository<WorkCenters> WorkCenterRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateWorkCenterHandler> logger;

        public CreateWorkCenterHandler(IMapper mapper, IBaseRepository<WorkCenters> workCenterRepository, ILogger<CreateWorkCenterHandler> logger)
        {
            this.mapper = mapper;
            WorkCenterRepository = workCenterRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 工作中心添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateWorkCenterCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var query = await (await WorkCenterRepository.GetAll()).Where(d => d.WorkCenterName == request.WorkCenterName ||  d.WorkCenterCode == request.WorkCenterCode).CountAsync();
                if (query > 0)
                {
                    result.Msg = "编码或名称已存在,请重新输入";
                }
                else
                {
                    WorkCenters workCenters = mapper.Map<WorkCenters>(request);
                    var res = await WorkCenterRepository.Add(workCenters);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Data = workCenters;
                        result.Msg = "工作中心添加成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "工作中心添加失败" + ex.Message;
                logger.LogError("工作中心添加失败" + ex.Message);
            }
            return result;
        }
    }
}
